<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }">
      <template #header>
        <div>
          <span>
            <el-button type="primary" size="default" @click="addTrademark" :icon="Plus">添加</el-button>
          </span>
        </div>
      </template>
      <!-- card body -->
      <el-table class="eltable" :data="tabelData" border stripe>
        <el-table-column align="center" label="序号" type="index" width="80"></el-table-column>
        <el-table-column align="center" prop="tmName" label="品牌名称"></el-table-column>
        <el-table-column align="center" prop="logoUrl" label="品牌Logo">
          <template #default="{ row }">
            <el-image style="height:50px" :src="row.logoUrl" :lazy="true"></el-image>
            <!-- <img height="50" :src="row.logoUrl" alt=""> -->
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <el-button @click="updateTrademark(row)" type="warning" size="small" :icon="Edit">修改</el-button>
            <el-button @click="detelaTrademark(row.id)" type="danger" size="small" :icon="DeleteFilled">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 

        current-page:当前页数，支持 v-model 双向绑定
        page-size:每页显示条目个数，支持 v-model 双向绑定
        page-sizes:每页显示个数选择器的选项设置
        pager-count:设置最大页码按钮数。 页码按钮的数量，当总页数超过该值时会折叠
        layout:组件布局，子组件名用逗号分隔
        total:总条目数
       -->
      <el-pagination v-model:currentPage="page" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]" :pager-count="5"
        layout=" sizes, prev, pager, next,total, jumper" :total="total" />
    </el-card>


    <el-dialog v-model="dialogFormVisible" :title="newTrademark.id ? '修改品牌' : '添加品牌'">
      <el-form ref="ruleFormRef" :model="newTrademark" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="newTrademark.tmName" autocomplete="off" />
        </el-form-item>
        <!-- 
        action:是图片上传的接口
       -->
        <el-form-item label="品牌Logo" prop="logoUrl">
          <el-upload class="avatar-uploader" :action="`${baseUrl}/admin/product/upload`" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="updateOrAddTradmark">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
  <script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Tradmark",
});
</script>
  
  <script setup lang="ts">
import { ref, toRefs, onMounted, watch, reactive } from "vue";
import { Plus, Edit, DeleteFilled } from "@element-plus/icons-vue";
import { requestAddTrademark, requestTrademarkList, requestUpdateTrademark, requestDeleteTrademark, type reqTrademarkReturnItemType } from '@/api/trademark'
import type { reqTrademarkReturnRecordsType } from '@/api/trademark'
import { ElMessageBox, type FormInstance, type FormRules, type UploadProps } from 'element-plus'

//1.table的逻辑
//table的的数据
const tabelData = ref<reqTrademarkReturnRecordsType>([]);


//2.页码逻辑
//页码的数据和类型
interface pageDateType {
  page: number,
  limit: number,
  total: number
}
const pageDate = ref<pageDateType>({
  page: 1,
  limit: 5,
  total: 100
})
//解构出页码的属性
const { total, limit, page } = toRefs(pageDate.value)

//监听页码改变,然后重新发送请求
watch([limit, page], () => {
  getTrademarkList()
})


//3.获取品牌列表
//封装获取品牌列表的函数
const getTrademarkList = async () => {
  const re = await requestTrademarkList({
    page: page.value, limit: limit.value
  })

  //把请求回来的数据设置给响应数据
  tabelData.value = re.records
  total.value = re.total
}
//初始化
onMounted(() => {
  //调用获取品牌列表的功能函数
  getTrademarkList()
});


//4.上传逻辑
//控制弹窗显示隐藏的数据
const dialogFormVisible = ref(false)

const baseUrl = import.meta.env.VITE_API_URL

const newTrademark = ref({
  logoUrl: '',
  tmName: '',
  id: 0
})
//上传逻辑
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // console.log(response.data);

  newTrademark.value.logoUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

//5.添加逻辑
const addTrademark = () => {
  //先清空上一次可能残留的校验信息
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  newTrademark.value = {
    logoUrl: '',
    tmName: '',
    id: 0
  }
}


//6.修改逻辑
const updateTrademark = (row: reqTrademarkReturnItemType) => {
  //先清空上一次残留的校验信息
  ruleFormRef.value?.clearValidate();
  dialogFormVisible.value = true;
  //获取当前的数据然后进行回填数据
  //拿到当前的数据浅拷贝赋值给表单的数据newTrademark(为了数据不会互相影响)
  newTrademark.value = { ...row }
}

//7.新增和修改提交
//获取form表单你的实例
const ruleFormRef = ref<FormInstance>()

const updateOrAddTradmark = async () => {
  //先进行全局校验
  try {
    //对整个表单的内容进行验证。 接收一个回调函数，或返回 Promise
    await ruleFormRef.value?.validate()
    //关闭弹窗
    dialogFormVisible.value = false;
    try {
      if (newTrademark.value.id) {
        //修改提交
        await requestUpdateTrademark(newTrademark.value);
        ElMessage.success("修改成功");
      } else {
        //新增提交
        await requestAddTrademark(newTrademark.value);
        ElMessage.success("新增成功");
        page.value = 1;
      }
    } catch (e) {
      ElMessage(newTrademark.value.id ? "修改错误" : "新增错误");
    }
    getTrademarkList();
  } catch (e) {

  }

}

//8.删除逻辑
const detelaTrademark = async (id: number) => {
  ElMessageBox.confirm(
    '确定要删除吗',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      try {
        await requestDeleteTrademark(id)
        getTrademarkList();

      } catch (e) {
        ElMessage.error('删除失败' + e)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消了吧',
      })
    })

}

//9.表单校验规则
//自定义表单规则函数
const checkTmNameLength = (rule: any, value: string, callback: any)=>{
/* 
rule:代表规则本身
value是当前需要被校验的值
callback是回调函数,如果有参数则代表错误信息 如果没有参数则代表放行
*/
if(value.length<2||value.length>5){
  callback('长度必须是2-5')
}else{
  callback()
}
}
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { validator:checkTmNameLength , message: '长度必须是3至5', trigger: 'blur' },
  ],
  logoUrl: [
    { required: true, message: '请上传品牌Logo', trigger: 'blur' }
  ]
})


</script>
  

<style scoped>
.eltable {
  margin-bottom: 20px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
  
  <style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>